import Joi from "joi";
import { ResultSetHeader, RowDataPacket } from "mysql2";
import { getDB } from "~/server/utils/db/mysql/index";
import { getLoginUid, responseJson } from "~/server/utils/helper/index";
/**
 * 1、判断用户是否登录
 * 2、已登录获取用户文章
 */

export default defineEventHandler(async (event) => {
  // 1、判断用户是否登录
  let uid = getLoginUid(event);
  if (uid === 0) {
    setResponseStatus(event, 401);
    return responseJson(1, "请登录", {});
  }

  const params = await getQuery(event);
  // 数据校验
  const schema = Joi.object({
    notebookId: Joi.number().required(),
  });
  try {
    await schema.validateAsync(params);
  } catch (error) {
    return responseJson(1, "参数错误", {});
  }

  const con = getDB();

  try {
    const [notebookRows] = await con.query<RowDataPacket[]>(
      "SELECT `note_id` FROM `notebook_notes` WHERE `notebook_id`=?",
      [params.notebookId]
    );
    let noteIdList: number[] = [];
    if (notebookRows.length < 1) {
      return responseJson(0, "无数据", {
        list: [],
      });
    }
    notebookRows.map((v) => {
      noteIdList.push(v.note_id);
    });
    const [notesRows] = await con.query<RowDataPacket[]>(
      "SELECT id,title FROM `notes` WHERE `uid`=? AND id IN (?) ORDER BY `id` DESC",
      [uid, noteIdList]
    );
    return responseJson(0, "获取文章成功哦", {
      list: notesRows,
    });
  } catch (error) {
    // 记录错误详情以便调试
    console.error("获取文章列表失败错误详情:", error);
    if (error instanceof Error) {
      console.error("错误消息:", error.message);
      console.error("错误堆栈:", error.stack);
    }
    return responseJson(1, "获取失败", {});
  }
  // 注意：不要关闭连接池！连接池应该保持打开状态以供后续使用
  // 连接池会自动管理连接的获取和释放
});
